<template>
  <div class="top-bar">
    <div class="w1230 top-main">
      <a href="../" class="toIndex">
        <i class="fa fa-home"></i>
        <span>爱购网首页</span>
      </a>
      <div class="account">
        <span>{{ loginUser.userName }}<i class="fa fa-caret-down"></i></span>
        <div class="manage">
          <ul>
            <li><RouterLink to="/deliverAddress">收货地址</RouterLink></li>
            <li><a href="../shoppingCart">我的购物车</a></li>
            <li><a href="../order">我的订单</a></li>
            <li><a v-if="loginUser!=null" href="" @click="logout">退出</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!--收货地址-->
  <div class="w1230">
    <img src="../assets/img/logo.png" width="100" height="40" class="logo"/>
    <span class="cart">购物车</span>
  </div>
  <div class="w1230 address">
    <div class="default" v-if="defaultAddress">
      <div class="default-title">收货地址</div>
      <div class="default-list">
        <span class="add-person">收货人：{{ defaultAddress.receivingPerson }}<span id="addName"></span></span>
        <div class="contact-info">
          <span class="add-tel">电话：{{ defaultAddress.mobilePhone }}</span>
          <el-button type="text" class="expand-button right-aligned" @click="toggleAddressVisibility">
            <span v-if="!isAddressVisible">展开收货地址</span>
            <span v-else>收起收货地址</span>
            <el-icon><i class="el-icon-search"></i></el-icon>
          </el-button>
        </div>
        <p class="add-address">收货地址：{{ defaultAddress.receivingAddress }}<span id="add"></span></p>
        <div v-if="isAddressVisible" class="address-list">
          <ul>
            <li v-for=" address in addresses" class="clear-float" :key="address.id">
              <input type="radio" name="address" class="single"
                     :value="address.id"
                     v-model="selectedAddressId"
                     @change="updateDefaultAddress"/>
              <div class="address-des">
                <span class="add-person">收件人：{{ address.receivingPerson }}</span>
                <span class="add-person">电话：{{ address.mobilePhone }}</span>
                <span class="add-person">收货地址：{{ address.receivingAddress }}</span>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="default" v-else>
      <div class="default-title">收货地址</div>
      <div class="default-list">
        <span class="add-person">收货人：{{ addresses[0].receivingPerson }}<span id="addName"></span></span>
        <div class="contact-info">
          <span class="add-tel">电话：{{ addresses[0].mobilePhone }}</span>
          <el-button type="text" class="expand-button right-aligned" @click="toggleAddressVisibility">
            <span v-if="!isAddressVisible">展开收货地址</span>
            <span v-else>收起收货地址</span>
            <el-icon><i class="el-icon-search"></i></el-icon>
          </el-button>
        </div>
        <p class="add-address">收货地址：{{ addresses[0].receivingAddress }}<span id="add"></span></p>
        <div v-if="isAddressVisible" class="address-list">
          <ul>
            <li v-for=" address in addresses" class="clear-float" :key="address.id">
              <input type="radio" name="address" class="single"
                     :value="address.id"
                     v-model="selectedAddressId"
                     @change="updateDefaultAddress"/>
              <div class="address-des">
                <span class="add-person">收件人：{{ address.receivingPerson }}</span>
                <span class="add-person">电话：{{ address.mobilePhone }}</span>
                <span class="add-person">收货地址：{{ address.receivingAddress }}</span>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!--购物车展示-->
  <div class="w1230 shopping ">
    <!--标题栏-->
    <div class="shopping-title">
      <ul class="clear-float">
        <li class="chk"><input type="checkbox" class="all-chk"/></li>
        <li class="info">商品信息</li>
        <li class="price">单价（元）</li>
        <li class="num">数量</li>
        <li class="min-price-title">小计（元）</li>
        <li class="operate">操作</li>
      </ul>
    </div>
    <!--详细展示-->
    <!--商品列表-->
    <div>
      <!-- 商品列表 -->
      <div class="shopping-list">
        <ul class="clear-float" v-for=" item in cartItems" :key="item.id">
          <li class="chk">
            <input type="checkbox" class="chkbox" v-model="item.checked"/>
          </li>
          <li class="info">
            <a target="_blank">
              <img :src="item.productImage"/>
              <p>{{ item.productName }}</p>
            </a>
          </li>
          <li class="price">{{ item.price.toFixed(2) }}</li>
          <li class="num">
            <a href="javascript:void(0)" class="minus"
               @click="updateProductNum(item.id, getProductNum(item.id) - 1)">-</a>
            <input type="text" :value="getProductNum(item.id)" class="num-val" readonly style="text-align: center;"/>
            <a href="javascript:void(0)" class="add"
               @click="updateProductNum(item.id, getProductNum(item.id) + 1)">+</a>
          </li>
          <li class="min-price">{{ (item.price * getProductNum(item.id)).toFixed(2) }}</li>
          <li class="operate">
            <a href="#" @click.prevent="delProduct(getCartId(item.id))">删除</a>
          </li>
        </ul>
      </div>

      <!-- 合计 -->
      <div class="shopping-footer clear-float">
        <div class="shopping-footer-l">
          <input type="checkbox" class="all-chk2 all-chk" v-model="allChecked" @change="toggleAll"/>
          <span>全选（共{{ selectedItemsCount }}件）</span>
          <span class="line">|</span>
          <a href="#" class="all-del" @click.prevent="batchDeleteProducts">批量删除</a>
        </div>
        <div class="shopping-footer-r">
          <span>已选商品<span class="choose-num">{{ selectedItemsCount }}</span>件</span>
          <span class="line">|</span>
          <span>合计：<span class="total">￥{{ totalPrice.toFixed(2) }}</span></span>
          <a href="#" class="compute">结算</a>
        </div>
      </div>
    </div>
  </div>
  <!--脚注-->
  <div class="footer">
    <p class="w1230">
      <a href="#">关于爱购</a>
      <a href="#">合作伙伴</a>
      <a href="#">营销中心</a>
      <a href="#">廉正举报</a>
      <a href="#">联系客服</a>
      <a href="#">开发平台</a>
      <a href="#">诚征英才</a>
      <a href="#">联系我们</a>
      <a href="#">网站地图</a>
      <a href="#">知识产权</a><span>|</span>
      <span>&copy;2018-2020 igo.com 版权所有</span>
    </p>
  </div>
  <router-view :key="$route.fullPath"></router-view>
</template>


<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "ShoppingCartView",
  data() {
    return {
      //当前用户
      loginUser: {},
      //当前用户的所有收货地址
      addresses: [],
      //当前用户的默认收货地址
      defaultAddress: [],
      //用于绑定选中的地址，进行地址的切换
      selectedAddressId: null,
      //控制收货列表的展示
      isAddressVisible: false,
      //商品列表
      cartItems: [],
      //单选框选择
      allChecked: false,
      //购物车
      shopCartProductList: []
    }
  },
  mounted() {
    this.loginUser = JSON.parse(localStorage.getItem("user"))
    console.log(this.loginUser)
    if (this.loginUser && this.loginUser.userId) {
      this.view(this.loginUser.userId)
      this.fetchCartItems(this.loginUser.userId)
      this.fetchCartProductItems(this.loginUser.userId)
    }
  },
  computed: {
    selectedItemsCount() {
      return this.cartItems.filter(item => item.checked).length;
    },
    totalPrice() {
      return this.cartItems
          .filter(item => item.checked)
          .reduce((total, item) => total + item.price * this.getProductNum(item.id), 0);
    }
  },
  methods: {
    logout() {
      this.loginUser = null
      localStorage.removeItem("user");
      this.$router.push("/");
    },
    updateDefaultAddress() {
      // 根据选中的地址ID更新默认地址
      this.defaultAddress = this.addresses.find(address => address.id === this.selectedAddressId);
    },
    //根据userId查询收货地址
    view(userId) {
      doGet("/user/shopCart/address/" + userId).then((resp) => {
        // 不管怎样，打印查看响应的resp 看看是否成功
        console.log(resp)
        // 200 表示成功，成功就可以进行数据绑定了，让后呈现数据了
        if (resp.data.code === 200) {
          // 查询此用户的所有收货地址
          this.addresses = resp.data.data
          // 查找默认地址
          this.defaultAddress = this.addresses.find(address => address.isDefault === 1);
          console.log("Addresses:", this.addresses);
          console.log("Default Address:", this.defaultAddress);

        }
      })
    },
    toggleAddressVisibility() {
      //更新isAddressVisible，控制列表的展示隐藏
      this.isAddressVisible = !this.isAddressVisible;
      console.log(this.isAddressVisible)
    },
    //根据userId查询对应购物车中的产品
    fetchCartItems(userId) {
      doGet("/user/shopCart/product/" + userId).then((resp) => {
        // 检查响应状态码
        if (resp.data.code === 200) {
          // 从响应数据中提取商品列表并更新cartItems数组
          this.cartItems = resp.data.data;
          console.log("cartItems", this.cartItems)
        }
      })
    },
    //设置全选
    toggleAll() {
      this.cartItems.forEach(item => {
        item.checked = this.allChecked;
      })
    },
    //根据userId查询购物车商品信息
    fetchCartProductItems(userId) {
      doGet("/user/shopCartProduct/user/" + userId).then((resp) => {
        // 检查响应状态码
        if (resp.data.code === 200) {
          // 从响应数据中提取商品列表并更新cartItems数组
          this.shopCartProductList = resp.data.data;
          console.log("shopCartProductList", this.shopCartProductList)
        }
      })
    },
    //获得产品数量
    getProductNum(id) {
      const product = this.shopCartProductList.find(item => item.productId === id);
      return product ? product.productNum : 0;
    },
    //获得购物车的id字段，购物车包含id，cart_id，product_id,product_num四个字段
    getCartId(id) {
      const Cart = this.shopCartProductList.find(item => item.productId === id);
      return Cart ? Cart.id : 0;
    },
    // 删除商品
    delProduct(id) {
      messageConfirm("是否删除该购物车商品？").then(() => {
        doDelete("/user/shopCartProduct/" + id).then((resp) => {
          if (resp.data.code === 200) {
            messageTip("删除成功!", "success")
            // 重新加载购物车商品列表以反映更改
            this.fetchCartItems(this.loginUser.userId)
          }
        })
      })
    },
    // 更新商品数量
    // 更新商品数量
    updateProductNum(id, newNum) {
      // 找到对应的商品
      const product = this.shopCartProductList.find(item => item.productId === id);
      if (product) {
        // 允许更新为0或大于0的数量
        if (newNum > 0) {
          // 更新前端显示的商品数量
          product.productNum = newNum;
          // 发送PUT请求到后端更新商品数量
          doPut(`/user/shopCartProduct/updateProductNum/${product.id}?productNum=${newNum}`)
              .then(response => {
                if (response.data.code === 200) {
                  // 如果后端更新成功，重新加载购物车商品列表以反映更改
                  this.fetchCartItems(this.loginUser.userId);
                } else {
                  // 如果后端更新失败，恢复原始数量并提示用户
                  product.productNum = this.getProductNum(id);
                  messageTip("更新数量失败，请重试", "error");
                }
              })
        } else {
          // 如果尝试将数量设置为负数，则提示用户并不改变数量
          messageTip("商品数量不能低于1", "warning");
        }
      }
    },
    // 批量删除商品
    batchDeleteProducts() {
      // 收集所有被选中的商品的ID
      const selectedProductIds = this.cartItems
          .filter(item => item.checked)
          .map(item => this.getCartId(item.id));

      // 如果没有选中的商品，则不执行删除操作
      if (selectedProductIds.length === 0) {
        messageTip("请先选择要删除的商品", "warning");
        return;
      }

      // 调用后端API进行批量删除
      doDelete(`/user/shopCartProduct/batchDelete/${selectedProductIds.join(',')}`).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("批量删除成功!", "success");
          // 重新加载购物车商品列表以反映更改
          this.fetchCartItems(this.loginUser.userId);
        } else {
          messageTip("批量删除失败，请重试", "error");
        }
      });
    },
  }
}
</script>
<style scoped>
@import '../assets/css/reset.css';
@import '../assets/css/top.css';
@import '../assets/css/shoppingCart.css';
@import '../assets/css/footer.css';
@import '../assets/css/font-awesome-4.7.0/Font-Awesome-master/css/font-awesome.min.css';

.contact-info {
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直方向居中对齐 */
  justify-content: space-between; /* 水平方向两端对齐，但我们需要进一步调整按钮的位置 */
}

.expand-button.right-aligned {
  /* 将按钮的margin-left设置为auto，以将其推到容器的最右侧 */
  margin-left: auto;
  /* 如果需要，可以添加其他样式来调整按钮的外观或大小 */
}

.address, .shopping {
  margin-bottom: 20px; /* 根据需要调整间距 */
  clear: both; /* 清除浮动，确保布局稳定 */
}
</style>